package com.hardydou.system.controller;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.StrUtil;
import com.hardydou.common.result.Code;
import com.hardydou.common.result.Result;
import com.hardydou.common.result.ResultHelper;
import com.hardydou.framework.filestore.AbstractFileStore;
import com.hardydou.framework.filestore.AbstractFileStore.*;
import com.hardydou.framework.filestore.FileStoreFactory;
import com.hardydou.framework.log.anno.LogMetaInfo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.IOException;
import java.util.*;

/**
 * @author ：hardy
 * @description：文件上传控制器
 * @date ：Created in 2020/6/15
 * @Copyright ：Hardydou.com
 */
@Controller
@RequestMapping("/upload")
@LogMetaInfo(module = "上传文件")
@Api(tags = "文件上传")
public class UploadController {
    @Autowired
    FileStoreFactory fileStoreFactory;

    @ApiIgnore
    @GetMapping("")
    public String index() {
        return "upload/index";
    }

    @PostMapping("/image")
    @ResponseBody
    public Result image(MultipartFile file, String busType) throws IOException {
        Result<Map<String, Object>> result;
        BusType bType = BusType.value(busType);
        String extName = FileTypeUtil.getType(file.getInputStream());
        if (StrUtil.isEmpty(extName)) {
            return ResultHelper.make(Code.UPLOAD_NO_SUPPORT_FORMAT);
        }
        AbstractFileStore fileStore = fileStoreFactory.getFileStore(FileType.IMAGE, bType, extName);
        if (!fileStore.isSafeExt()) {
            return ResultHelper.make(Code.UPLOAD_NO_SUPPORT_FORMAT);
        }
        fileStore.write(file.getInputStream());
        result = ResultHelper.ok();
        result.getData().put("url", fileStore.getReqPath());
        return result;
    }


}
